package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.User;
import com.itheima.service.IUserSevice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.List;

import static com.itheima.controller.Code.*;

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private IUserSevice iUserSevice;

	//分页查询用户
    @GetMapping("/{currentPage}/{pageSize}")
    public Result selectByPage(@PathVariable  int currentPage,@PathVariable int pageSize) throws IOException {
        IPage<User> page = new Page<>(currentPage, pageSize);
        iUserSevice.page(page,null);
        Result result = new Result();
        if (page.getRecords() !=null){
            PageBean pageBean = new PageBean(page.getRecords(), page.getTotal());
            result.setCode(GET_OK);
            result.setMsg("分页查询成功");
            result.setData(pageBean);
            return result;
        }
        result.setCode(GET_ERR);
        result.setMsg("分页查询失败");
        return result;

    }
    /**
     * 保存用户
     * @param user 用户数据
     */
    @PostMapping
    public Result add(@RequestBody  User user) {
        boolean save = iUserSevice.save(user);
        Result result = new Result();
        if (save){
            result.setCode(SAVE_OK);
            result.setMsg("添加成功");
            return result;
        }
        result.setCode(SAVE_ERR);
        return result;
    }

    /**
     * 根据用户id查询用户
     * @param id 用户id
     */
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id) {
        Result result = new Result();
        boolean remove = iUserSevice.removeById(id);
        System.out.println("remove = " + remove);
        if (remove){
            result.setCode(DELETE_OK);
            result.setMsg("删除成功");
            return result;
        }
        result.setCode(DELETE_ERR);
        result.setMsg("删除失败");
        return result;
    }

    /**
     * 更新用户
     * @param user 用户数据
     */
    @PutMapping
    public Result update(@RequestBody User user) {
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getId,user.getId());
        Result result = new Result();
        boolean update = iUserSevice.update(user, qw);
        if (update){
            result.setCode(UPDATE_OK);
            result.setMsg("更新成功");
            return result;
        }
        result.setCode(UPDATE_ERR);
        result.setMsg("更新失败");
        return result;
    }

}
